import pandas as pd
import numpy as np
from SKO.AbstractDPJob import AbstractDPJob
import joblib
import xgboost as xgb

class Predict_JTindexJob(AbstractDPJob):
    def __init__(self,
                 p_index_name=None, p_df_X=None):

        super(Predict_JTindexJob, self).__init__()
        self.index_name = p_index_name
        self.df_X = p_df_X
        pass
    def execute(self):
        return self.do_execute()
    def do_execute(self):
        super(Predict_JTindexJob, self).do_execute()
        index_name = self.index_name
        df_X = self.df_X
        target_tmp = index_name
        X_pred = df_X
        target_list = ['Ad_JT', 'St,d', 'DI', 'M40', 'M10', 'CSR', 'CRI']
        feature_names = ['Mt', 'Ad', 'Vd', 'Std', 'GRI', 'Y', 'FlowDegree', 'a+b', 'C', 'Qnet_d', 'Fe2O3', 'SiO2',
                         'CaO', 'Al2O3', 'MgO', 'TiO2', 'MnO', 'P2O5', 'S', 'Zn', 'Pb', 'Na2O', 'K2O', 'VITRI']
        index = target_list.index(target_tmp)
        print(f"target_tmp 在 target_list 中的索引位置是：{index}")
        txt_name = 'my_list_' + str(index) + '.txt'
        # xlsx_name = 'D:/repos/sicost/12月新/新数据.xlsx'
        # X_pred = pd.read_excel(xlsx_name)
        with open(txt_name, 'r') as file:
            # 读取文件内容
            list_str = file.read()
            # 使用逗号分隔字符串，并转换回list
            my_list_from_file = list(map(int, list_str.split(',')))
        # 打印读取的list
        print(my_list_from_file)
        model_file = 'xgb_regression_model_' + str(index) + '.joblib'
        # # 从本地文件读取模型
        loaded_bst = joblib.load(model_file)
        selected_feature_indices = my_list_from_file
        X_pred_selected = X_pred.iloc[:, selected_feature_indices]
        X_pred_selected = X_pred.copy()
        dtest = xgb.DMatrix(X_pred_selected)
        # 使用加载的模型进行预测
        y_pred = loaded_bst.predict(dtest)
        y_pred = float(y_pred)
        print(y_pred)
        return y_pred
